package com.eva.ss;

import com.eva.dao.system.model.SystemUser;
import com.eva.framework.common.constants.ResponseStatus;
import com.eva.framework.common.exception.BusinessException;
import com.eva.service.system.SystemUserService;
import com.eva.ss.model.SsUserInfo;
import com.eva.ss.service.LoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * UserDetailsService的默认实现
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SystemUserService systemUserService;

    @Resource
    private LoginService loginService;

    /**
     * 根据用户名查询用户，包含权限信息
     *
     * @param username 用户名
     * @return LoginUserInfo
     * @throws UsernameNotFoundException UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUser queryDto = new SystemUser();
        queryDto.setUsername(username);
        SystemUser user = systemUserService.findOne(queryDto);
        if (user == null) {
            throw new BusinessException(ResponseStatus.ACCOUNT_INCORRECT);
        }
        SsUserInfo loginUserInfo =  new SsUserInfo();
        BeanUtils.copyProperties(user, loginUserInfo);
        // 补充用户信息
        loginService.padding(loginUserInfo);
        return loginUserInfo;
    }
}
